package com.liugh.shiro;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.liugh.config.jackson.HandlerIgnoreMixin;
import com.liugh.config.jackson.LocalDateDeserializer;
import com.liugh.config.jackson.LocalDateSerializer;
import com.monitorjbl.json.JsonViewSupportFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.time.LocalDate;
import java.util.List;

/**
 * @author liugh
 * @since 2018-05-03
 */
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        super.addInterceptors(registry);
    }

    // ----------------- jackson相关 --------------------


    /**
     * jackson配置.
     * @return
     */
    @Bean
    @Primary
    public ObjectMapper objectMapper() {
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer());       // localDate to timestamp
        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer());       // localDate to timestamp
        return new ObjectMapper()
                .registerModule(javaTimeModule)
                .addMixIn(Object.class, HandlerIgnoreMixin.class)           // 忽略handler属性, 后续参考：https://stackoverflow.com/questions/8235255/global-property-filter-in-jackson
                .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
//              .setSerializationInclusion(JsonInclude.Include.NON_NULL)    // 忽略空属性
                .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
//                .disable(MapperFeature.DEFAULT_VIEW_INCLUSION)          // 在添加了jsonview 的情况下，没有用注解标志的属性不转换成json
                .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);// 允许空对象
    }

    /*
     * 补丁，目前jackson还不支持动态忽略某一个属性，因此使用这个库来实现
     * @return
     */
    @Bean
    public JsonViewSupportFactoryBean views() {
        return new JsonViewSupportFactoryBean(objectMapper());      // 在全局objectMapper的基础上通过convert修改
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(currentUserMethodArgumentResolver());
        super.addArgumentResolvers(argumentResolvers);
    }

    @Bean
    public CurrentUserMethodArgumentResolver currentUserMethodArgumentResolver() {
        return new CurrentUserMethodArgumentResolver();
    }
}
